package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exeception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author SunSun
 * @date 2021/11/1
 */
@Service
public class SmallVideosService {
    @DubboReference
    private VideoApi videoApi;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private MqMessageService mqMessageService;

    @DubboReference
    private CommentApi commentApi;

    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        if (videoFile.isEmpty()||videoFile.isEmpty()){
            throw new  BusinessException(ErrorResult.error());
        }
        String filename = videoFile.getOriginalFilename();
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videourl =webServer.getWebServerUrl()+storePath.getFullPath();
        String imageurl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        Video video=new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageurl);
        video.setVideoUrl(videourl);
        video.setText("你的酒窝没有就,我却醉的像条狗");
        String videoId=videoApi.save(video);
        if(StringUtils.isEmpty(videoId)){
            throw  new BusinessException(ErrorResult.error());
        }

        mqMessageService.sendLogMessage(UserHolder.getUserId(),"0301","video",videoId);
    }

    /**
     * 查询视频列表
     * @param page
     * @param pagesize
     * @return
     */
    @Cacheable(
            value = "videos",
        key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize"
    )
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        String rediskey=Constants.VIDEOS_RECOMMEND+UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(rediskey);

        List<Video> list=new ArrayList<>();
        int totalPage =0;
        if(!StringUtils.isEmpty(redisValue)){
            String[] split = redisValue.split(",");

            if((page-1)*pagesize<split.length){
                List<Long> vids = Arrays.stream(split).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                list=videoApi.findVideos(vids);
            }
            totalPage = PageUtil.totalPage(split.length, page);
        }
        if (list.isEmpty()){
            list=videoApi.queryVideosList((page-totalPage),pagesize);
        }

        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);

        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);

        List<VideoVo> vos=new ArrayList<>();
        for (Video video : list) {
            UserInfo userInfo = map.get(video.getUserId());
            if(userInfo!=null){
                VideoVo vo = VideoVo.init(userInfo, video);
                String key=Constants.FOCUS_USER_KEY+UserHolder.getUserId();
                String hashKey=String.valueOf(video.getUserId());
                //加入了作者关注功能，从redis判断是否存在关注的key，如果存在设置hasFocus=1
                if(redisTemplate.opsForHash().hasKey(key,
                        hashKey)) {
                    vo.setHasFocus(1);
                }

                String loveKey= Constants.MOVEMENTS_INTERACT_KEY+video.getId();
                String loveHashkey=Constants.VIDEO_LIKE_HASHKEY+UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(loveKey,
                        loveHashkey)){
                    vo.setHasLiked(1);
                }

                vos.add(vo);
            }
        }

        return new PageResult(page,pagesize,0l,vos);
    }

    public void userFocus(Long followUserId) {
        FocusUser focusUser=new FocusUser();
        focusUser.setUserId(UserHolder.getUserId());
        focusUser.setFollowUserId(followUserId);
        focusUser.setCreated(System.currentTimeMillis());
        videoApi.saveFocusUser(focusUser);

        String key=Constants.FOCUS_USER_KEY+UserHolder.getUserId();
        String hashKey=String.valueOf(followUserId);
        redisTemplate.opsForHash().put(key,hashKey,"1");
    }

    //取消关注视频作者
    public void userUnFocus(Long followUserId) {
        //1、调用API删除关注数据
        videoApi.deleteFollowUser(UserHolder.getUserId(),followUserId);
        //2、删除redis中关注记录
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        String hashKey = String.valueOf(followUserId);
        redisTemplate.opsForHash().delete(key,hashKey);
    }

    public Integer likecomment(String ID) {
        Long userId = UserHolder.getUserId();

        boolean hasComment=commentApi.likecomment(userId,ID,CommentType.LIKE);

        if(hasComment){
            throw new BusinessException(ErrorResult.likeError());
        }

        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(ID));
        comment.setUserId(userId);
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setCreated(System.currentTimeMillis());

        Integer count = commentApi.saveVideo(comment);

        String key= Constants.MOVEMENTS_INTERACT_KEY+ID;
        String hashkey=Constants.VIDEO_LIKE_HASHKEY+userId;
        redisTemplate.opsForHash().put(key,hashkey,"1");
        return count;
    }

    public Integer dislikecomment(String videoID) {
        Long userId = UserHolder.getUserId();
        boolean hasComment=commentApi.likecomment(userId,videoID,CommentType.LIKE);
        if(!hasComment){
            throw new BusinessException(ErrorResult.disLikeError());
        }

        Comment comment=new Comment();
        comment.setPublishId(new ObjectId(videoID));
        comment.setUserId(userId);
        comment.setCommentType(CommentType.LIKE.getType());

        Integer count = commentApi.deleteVideo(comment);
        String key= Constants.MOVEMENTS_INTERACT_KEY+videoID;
        String hashkey=Constants.VIDEO_LIKE_HASHKEY+userId;
        redisTemplate.opsForHash().delete(key,hashkey);
        return count;
    }

    public void saveComment(String comment, String videoId) {
        Long userId = UserHolder.getUserId();

        Comment comment1=new Comment();
        comment1.setPublishId(new ObjectId(videoId));
        comment1.setUserId(userId);
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setCreated(System.currentTimeMillis());

        Integer commentCount=commentApi.saveVideo(comment1);
    }

    public PageResult findComments(Integer page, Integer pagesize, String videoId) {
        List<Comment> list=commentApi.findComments(videoId,CommentType.COMMENT,page,pagesize);

        if(CollUtil.isEmpty(list)){
            return new PageResult();
        }

        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> byIds = userInfoApi.findByIds(userIds, null);

        List<CommentVo> lists=new ArrayList<>();

        for (Comment comment : list) {
            UserInfo userInfo = byIds.get(comment.getUserId());
            if(userInfo!=null){
                CommentVo commentVo=CommentVo.init(userInfo,comment);
                //修复点赞bug
                String key= Constants.MOVEMENTS_INTERACT_KEY+comment.getId();
                String hashkey=Constants.VIDEO_LIKE_HASHKEY+UserHolder.getUserId();
                if(redisTemplate.opsForHash().hasKey(key,hashkey)){
                    commentVo.setHasLiked(1);
                }
                lists.add(commentVo);
            }
        }

        return new PageResult(page,pagesize,0l,lists);
    }
}
